import os
import random
import string
import time
from urllib.parse import urlparse

from segment_anything import SamPredictor, sam_model_registry

#
predictor = None  # 定义predictor为全局变量
global_start_time = time.time()
model_path = os.getenv('MODELSCOPE_CACHE_EMBEDDING', "C:/Users/Administrator/Downloads/sam_vit_h_4b8939.pth")
checkpoint = model_path
# checkpoint = "/root/.cache/sam_vit_h_4b8939.pth"
model_type = "vit_h"


def load_predictor(model_type, checkpoint):
    start_time = time.time()
    model = sam_model_registry[model_type](checkpoint=checkpoint)
    model.to(device='cuda')
    global predictor  # 这里使用全局变量predictor
    predictor = SamPredictor(model)
    end_time = time.time()
    print("load model time: ", end_time - start_time)
    return predictor


# 加载模型


def get_random_string(length):
    return ''.join(random.choices(string.ascii_lowercase + string.digits, k=length))


def get_file_prefix():
    # return "d:/tmp/output"
    return "/mnt/output"


def get_local_dir():
    # return "d:/tmp"
    return "/tmp"


def get_oss_file_url(file_name):
    return f"lama/{file_name}"


def get_request_filename(url):
    parsed_url = urlparse(url)
    path = parsed_url.path
    return os.path.basename(path)


def get_file_name_no_ext(file_name):
    filename_without_ext, _ = os.path.splitext(file_name)
    return filename_without_ext

# if __name__ == '__main__':
#     # process_image("bird.png")
#     process_image("phone.png")
